﻿using System.IO;
using System.Text;
using System.Web;
using System.Web.SessionState;
using Newtonsoft.Json;

namespace AssetManage.Handler
{
    public class Captcha : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext currentContext)
        {
            var responseJsonStringBuilder = new StringBuilder();
            var responseJsonStringWriter = new StringWriter(responseJsonStringBuilder);

            var responseJsonWriter = new JsonTextWriter(responseJsonStringWriter) {Formatting = Formatting.Indented};
            responseJsonWriter.WriteStartObject();

            var newCaptcha = new Web.Security.Captcha();
            var imageStream = new MemoryStream();
            newCaptcha.CreateImage(imageStream);
            currentContext.Session["CAPTCHA"] = newCaptcha.ValidationCode;
            currentContext.Response.ClearContent();
            currentContext.Response.ContentType = "image/gif";
            currentContext.Response.BinaryWrite(imageStream.ToArray());
            currentContext.Response.End();
        }

        public bool IsReusable
        {
            get { return false; }
        }
    }
}